package edu.ccut.saturn.authority.impl.filter;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import edu.ccut.saturn.authority.impl.authority.AuthorityMapping;
import edu.ccut.saturn.component.FilterManager;
import edu.ccut.saturn.component.ISaturnFilter;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.component.SaturnResponse;

public class SaturnAuthorityFilter implements ISaturnFilter {
	
	private static final String ERROR_PAGE = "/login.jsp";

	@SuppressWarnings("unchecked")
	public SaturnResponse doFilter(HttpServletRequest request) {
		String loginAction = request.getRequestURI();
		loginAction = loginAction.substring(1);
		loginAction = loginAction.substring(loginAction.indexOf("/"));
		loginAction = loginAction.replace("::", "");
		FilterManager filterManager = FilterManager.getInstance();	
		Map<String,List<String>> authorityMapping = AuthorityMapping.getInstance().getAuthorityMapping();
		List<String> publicResources =  authorityMapping.get("publicResources");
		for(String publicResource:publicResources){
			if(filterManager.isFullMatching(loginAction, publicResource)){
				return SaturnResponse.sendRedirect();
			}
		}
		List<SaturnData> authresources = (List<SaturnData>) request.getSession().getAttribute(
		"_SATURN_AUTHRESOURCE_LIST_");
		if(authresources != null){
			
			for(SaturnData authresource:authresources){
				String id = (String) authresource.get("id");
				List<String> paths = authorityMapping.get(id);
				for(String path:paths){
					if(filterManager.isFullMatching(loginAction, path)){
						return SaturnResponse.sendRedirect();
					}
				}			
			}
		}
		String contextPath = request.getContextPath();
		return SaturnResponse.sendRedirect(contextPath+ERROR_PAGE);
	}
}
